<template>
    <div width="100%">
        <el-card width="100%">
            <template #header>
                <h2>警员账号数据</h2>
            </template>
            <el-form inline width="100%" :model="searchParams" @submit.native.prevent>
                <el-form-item label="账号用户名">
                    <el-input v-model="searchParams.name" placeholder="请输入用户名" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="fetchData">搜索</el-button>
                    <el-button type="default" @click="reset">重置</el-button>
                    <el-button type="default" @click="openAddUser">添加</el-button>
                </el-form-item>
            </el-form>
            <el-scrollbar height="400">
                <el-table :data="tableData" width="100%">
                    <el-table-column type="index" width="80" />
                    <el-table-column prop="username" label="账号用户名" width="100" />
                    <el-table-column prop="passwordHash" label="账号密码" width="100" />
                    <el-table-column prop="policeOfficer.name" label="警员姓名" width="80" />
                    <el-table-column prop="policeOfficer.officerId" label="警员ID" width="80">
                        <template #default="scope">
                            <div>
                                <el-tag type="primary">{{ 'P' + scope.row.policeOfficer.officerId }}</el-tag>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="role" label="职责" />
                    <el-table-column prop="lastLogin" label="上次登录时间" :formatter="formatDate" />
                    <el-table-column prop="createdAt" label="创建时间" :formatter="formatDate" />
                    <el-table-column label="操作" width="200">
                        <template #default="scope">
                            <el-button type="success" size="small" @click="editUser(scope.row)">编辑</el-button>
                            <el-button type="danger" size="small" @click="confirmDeleteUser(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-scrollbar>

            <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                :page-sizes="[5, 10, 20, 50]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" width="100%" />
        </el-card>
        
        <!-- 弹窗 -->
        <el-dialog v-model="dialogFormVisible" :title="title" width="700">
            <el-form :model="accountInfo" :rules="rules" ref="accountInfoForm" @submit.native.prevent>
                <el-form-item label="账号用户名" label-width="100px" prop="username">
                    <el-input v-model="accountInfo.username" />
                </el-form-item>
                <el-form-item label="密码" label-width="100px" prop="passwordHash">
                    <el-input v-model="accountInfo.passwordHash" />
                </el-form-item>
                <el-form-item label="警号" label-width="100px" prop="officerId">
                    <!-- 在表单前面加一个蓝色的P,div时水平的 -->
                    <div style="display: flex; align-items: center;">
                        <el-tag type="primary">P</el-tag>
                        <el-input v-model="accountInfo.officerId" :disabled="accountInfo.isOfficerIdDisabled" />
                    </div>
                </el-form-item>
                <el-form-item label="职责" label-width="100px" prop="role">
                    <el-select v-model="accountInfo.role" placeholder="请选择职责">
                        <el-option label="一般警员" :value="2"></el-option>
                        <el-option label="系统管理员" :value="1"></el-option>
                    </el-select>
                </el-form-item>
                <span class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveOrUpdateAccountInfo">确定</el-button>
                </span>
            </el-form>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { getOfficerAccountPage, addOfficerAccount, updateOfficerAccount, deleteOfficerAccount } from '@/api/police';
import { ElMessage, ElMessageBox } from 'element-plus';


onMounted(() => {
    fetchData();
});
const rules = {
    username: [
        { required: true, message: '账号用户名不能为空', trigger: 'blur' },
        { min: 3, message: '账号用户名长度不能少于3个字符', trigger: 'blur' }
    ],
    passwordHash: [
        { required: true, message: '密码不能为空', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
    ],
    officerId: [
        { required: true, message: '警号不能为空', trigger: 'blur' }
    ],
    role: [
        { required: true, message: '请选择职责', trigger: 'change' }
    ]
};

const search = () => {
    fetchData();
};

const reset = () => {
    searchParams.name = '';
    fetchData();
};

const formatDate = (row, column, cellValue) => {
    const date = new Date(cellValue);
    return date.getFullYear() + '年' + (date.getMonth() + 1) + '月' + date.getDate() + '日' + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
};

const confirmDeleteUser = (row) => {
    ElMessageBox.confirm(`确定要删除这个账号 ${row.name} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        deleteUser(row);
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
};
let flag = true;

const deleteUser = async (row) => {
    const { data } = await deleteOfficerAccount(row.accountId);
    if (data.code === 2000) {
        ElMessage.success(data.message);
    } else {
        ElMessage.error(data.message);
    }
    flag = false;
    fetchData(flag);
};

const searchParams = reactive({
    name: ''
});

const tableData = ref([]);
const pagination = reactive({
    currentPage: 1,
    pageSize: 5,
    total: 0
});

const dialogFormVisible = ref(false);
const title = ref('分配警员账号');
const accountInfo = reactive({
    username: '',
    passwordHash: '',
    officerId: '',
    role: '',
    isOfficerIdDisabled: false,
});

const fetchData = async (flag) => {
    if (flag === false) {
        pagination.currentPage = 1;
    }
    const { data } = await getOfficerAccountPage({
        currentPage: pagination.currentPage,
        pageSize: pagination.pageSize,
        name: searchParams.name
    });
    if (data.code === 2000) {
        tableData.value = data.data;
        tableData.value.forEach(item => {
            item.role = item.role === 1 ? '系统管理员' : '一般警员';
        });
        pagination.total = data.total;
    } else {
        ElMessage.error(data.message);
    }
};

const handleDelete = (row) => {
    confirmDeleteUser(row);
};

const handleEdit = (row) => {
    editUser(row);
};

const handleAdd = () => {
    openAddUser();
};

const handleSelectionChange = (val) => {
    console.log(val);
    pagination.total = data.total;
};

const handleSizeChange = (size) => {
    pagination.pageSize = size;
    fetchData();
};

const handleCurrentChange = (page) => {
    pagination.currentPage = page;
    fetchData();
};

const openAddUser = () => {
    dialogFormVisible.value = true;
    title.value = '添加警员账号';
    accountInfo.isOfficerIdDisabled = false;
    Object.assign(accountInfo, {
        username: '',
        passwordHash: '',
        officerId: '',
        role: '',
    });
    accountInfoForm.value.resetFields();
};

const accountInfoForm = ref(null);

const saveOrUpdateAccountInfo = async () => {
    if (!accountInfoForm.value) return;
    await accountInfoForm.value.validate(async (valid) => {
        if (valid) {
            if (title.value === '添加警员账号') {
                const { data } = await addOfficerAccount(accountInfo);
                if (data.code === 2000) {
                    ElMessage.success(data.message);
                } else {
                    ElMessage.error(data.message);
                }
            } else {
                if (accountInfo.role === '系统管理员') {
                    accountInfo.role = 1;
                } else if (accountInfo.role === '一般警员') {
                    accountInfo.role = 2;
                }
                const { data } = await updateOfficerAccount(accountInfo);
                if (data.code === 2000) {
                    ElMessage.success(data.message);
                } else {
                    ElMessage.error(data.message);
                }
            }
            dialogFormVisible.value = false;
            fetchData();
        } else {
            ElMessage.error('表单校验失败，请检查输入的内容');
        }
    });
};

const editUser = (row) => {
    dialogFormVisible.value = true;
    title.value = '编辑警员账号';
    accountInfo.isOfficerIdDisabled = true;
    Object.assign(accountInfo, row, {
        role: row.role === '系统管理员' ? 1 : 2
    });
};
</script>

<style scoped>
.el-form-item {
    margin-bottom: 20px;
}
.dialog-footer {
    text-align: right;
}
</style>
